<template>
  <div class="app-container tz-app">


    <div class="zt-select flex-s">
      <div class="flex-left flex">
        <!-- <el-select v-model="queryParams.radioStationName" filterable placeholder="电台名称" class="zt-input rihgt-m5" clearable>
          <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.label">
          </el-option>
        </el-select> -->
        <el-input class="zt-input rihgt-m5" v-model="queryParams.sensorName" placeholder="传感器名称" />
        <button class="bt-blue " @click="handleQuery">筛选</button>
        <!-- 
        <el-select v-model="queryParams.sensorType" filterable placeholder="传感器" class="zt-input-min rihgt-m5" clearable>
          <el-option v-for="item in  dict.type.sensor_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <button class="bt-blue " @click="handleQuery">筛选</button> -->

      </div>
      <div class="red flex-right" v-show="sensorListAll.visible">有新的传感器入网，请编辑</div>

    </div>


    <div class="tz-table-box" style="height:calc(100vh - 250px);">
      <el-table v-loading="loading" :data="sensorList" @selection-change="handleSelectionChange"
        height="calc(100vh - 250px)" class="zt-table">
        <el-table-column type="index" width="50"> </el-table-column>
        <!-- <el-table-column show-overflow-tooltip label="传感器ID" align="center" prop="sensorId" /> -->
        <el-table-column show-overflow-tooltip label="传感器名称" align="center" prop="sensorName" >
          <template slot-scope="scope">
            <div :class="{ 'red': scope.row.isNet == 0 }">{{ scope.row.sensorName }}</div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="传感器编码" align="center" prop="sensorCode" width="160"/>
        <el-table-column show-overflow-tooltip label="创建时间" align="center" prop="createTime" width="190" sortable />
        <el-table-column show-overflow-tooltip label="传感器类型" align="center" prop="inoutType" sortable>
          <template slot-scope="scope">
            {{ getSensorType(scope.row.inoutType) }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="所属地址" align="center" prop="locatedAddress" sortable>
          <template slot-scope="scope">
            {{ getLocatedAddress(scope.row.locatedAddress) }}
          </template>
        </el-table-column>

        <!-- <el-table-column show-overflow-tooltip label="使用状态" align="center" prop="isUsed" /> -->
        <!-- <el-table-column show-overflow-tooltip label="传感器属性" align="center" prop="sensorAttribute" /> -->
        <el-table-column show-overflow-tooltip label="所属台站" align="center" prop="regionalNodeName" sortable />
        <el-table-column show-overflow-tooltip label="所属机房" align="center" prop="machineRoomName" sortable />
        <el-table-column show-overflow-tooltip label="状态" align="center" prop="status" sortable>
          <template slot-scope="scope">
            <div>{{ scope.row.status == 0 ? '正常' : '异常' }}</div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="入网状态" align="center" prop="isNet" sortable>
          <template slot-scope="scope">
            <div :class="{ 'red': scope.row.isNet == 0 }">{{ scope.row.isNet == 0 ? '未入网' : '已入网' }}</div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="操作" align="center" class-name="small-padding fixed-width"
          width="180">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:sensor:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:sensor:remove']">删除</el-button> -->

            <img src="@/assets/images/amend.png"
              style="width: 20px;height: 20px;cursor: pointer;margin-top: 10px; margin-right: 20px;"
              @click="handleUpdate(scope.row)" title="编辑" />
            <img src="@/assets/images/delete-bin2.png"
              style="width: 20px;height: 20px;cursor: pointer;margin-top: 10px; margin-right: 20px;"
              @click="handleDelete(scope.row)" title="删除" />

            <el-popover placement="top-start" popper-class="zt-popper" width="280" trigger="click"
              @after-enter="sensorAttributeOpen(scope.row)" @hide="sensorAttributeClose">
              <template #reference>
                <img src="@/assets/images/xs.png" style="width: 20px;height: 20px;margin-top: 10px; cursor: pointer;"
                  title="状态">
              </template>
              <template v-show="popoverOpen" #default>
                <div class="flex message-popup">
                  <div>
                    <div v-for="(item, index) in sensorAttribute" :key="index" style="color: #25CAD5;font-size: 16px;">
                      {{ item.name }}:{{ item.value }}
                    </div>
                  </div>
                </div>
              </template>
            </el-popover>


            <img src="@/assets/images/flashlight1.png" v-show="scope.row.isPower == 1"
              style="width: 20px;height: 20px;cursor: pointer;margin-top: 10px; margin-left: 20px;"
              @click="handleDelete(scope.row)" />
            <div style="width: 20px;height: 20px;margin-top: 10px; margin-left: 20px; display: inline;"
              v-show="scope.row.isPower != 1"></div>
          </template>
        </el-table-column>
      </el-table>

    </div>



    <div class="zt-pagination">
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>


    <right-dialog :title="title" :visible="open" @closeDialog="cancel">
      <template v-slot:default>
        <div class="zt-dialog-solt">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="传感器名称:" prop="sensorName">
              <div class="flex">
                <el-input class="blue-input" v-model="form.sensorName" placeholder="请输入传感器名称" />
                <el-button class="bt-blue " @click="submitForm" style="margin-left: 10px; ">{{ title == '添加传感器' ? '添加' :
          '确定'
                  }}</el-button>
              </div>
            </el-form-item>
            <div class="flex">
              <el-form-item label="传感器类型:" prop="inoutType">
                <el-select v-model="form.inoutType" filterable placeholder="传感器类型" class="zt-input-min rihgt-m5">
                  <el-option v-for="item in  dict.type.inout_type" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="所属地:" prop="locatedAddress">
                <el-select v-model="form.locatedAddress" filterable placeholder="所属地" class="zt-input-min rihgt-m5">
                  <el-option v-for="item in  dict.type.located_address" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>

              <!-- <el-form-item label="入网状态:"   v-model="form.isNet"> -->
              <el-form-item label="入网状态:" v-if="isNet == 0" v-model="form.isNet">
                <el-select filterable v-model="form.isNet" class="zt-input-min rihgt-m5">
                  <el-option :key="0" label="未入网" value="0" />
                  <el-option :key="1" label="已入网" value="1" />
                </el-select>
              </el-form-item>
            </div>
            <div class="flex">
              <el-form-item label="供应商:">
                <el-input class="zt-input-min" v-model="form.supplier" placeholder="请输入供应商" />
              </el-form-item>
              <el-form-item label="出厂日期:">
                <el-date-picker class="zt-input-min" value-format="yyyy-MM-dd" v-model="form.deliveryTime" type="date"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </div>

            <el-form-item label="开关:">
              <el-switch v-model="form.isPower" active-color="#13ce66" active-value="1" inactive-value="0">
              </el-switch>
            </el-form-item>


            <el-form-item label="备注:" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>

        </div>
      </template>
    </right-dialog>


  </div>
</template>

<script>
import { listSensor, getSensor, delSensor, addSensor, updateSensor, getSensorListAll } from "@/api/business/sensor";
import RightDialog from "@/components/TZ/RightDialog"
export default {
  name: "Sensor",
  components: { RightDialog },
  dicts: ['located_address', 'sensor_type', 'sensor_code', 'inout_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 传感器表格数据
      sensorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sensorName: null,
        sensorType: null,
        sensorAttribute: null,
        status: null,
      },
      arr: [
        { "name": "W湿度", "value": 62.9 }, { "name": "N温度", "value": 8.3 }, { "name": "N湿度", "value": 61.5 },
        { "name": "风速", "value": 60 }, { "name": "风向", "value": '西北风' }, { "name": "雨量", "value": 61.5 },
        { "name": "W温度", "value": 90 }, { "name": "风力", "value": '100' }
      ],
      arrs: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sensorName: [
          { required: true, message: "传感器名称不能为空", trigger: "change" }
        ],
        sensorType: [
          { required: true, message: "传感器类型不能为空", trigger: "change" }
        ],
        sensorAttribute: [
          { required: true, message: "传感器属性不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        inoutType: [
          { required: true, message: "传感器类型不能为空", trigger: "change" }
        ],
        locatedAddress: [
          { required: true, message: "所屬地不能为空", trigger: "change" }
        ],

      },
      isNet: null,
      sensorAttribute: {},
      popoverOpen: false,
      sensorListAll: {
        visible: false,
        total: 0,
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.startTimer();
  },
  beforeDestroy() {
    // 在组件销毁前清理定时器
    this.stopTimer();
  },
  methods: {
    fetchData() {
      // 发送请求获取数据的逻辑

      const data = {
        isNet: 0
      }
      getSensorListAll(data).then(response => {
        this.sensorListAll.visible = response.total != this.sensorListAll.total ? true : false
        // console.log("this.sensorListAll.visible",this.sensorListAll.visible);
        // console.log(" response.total ", response.total );
        // console.log("this.sensorListAll.total", this.sensorListAll.total );
        this.sensorListAll.total = response.total
      });
    },
    startTimer() {
      // 启动定时器，每一分钟请求一次数据
      this.timer = setInterval(() => {
        this.fetchData();
        // }, 5000); // 60000毫秒等于1分钟
      }, 60000); // 60000毫秒等于1分钟
    },
    stopTimer() {
      // 销毁定时器
      clearInterval(this.timer);
    },
    sensorAttributeClose() {//清除传感器属性
      this.sensorAttribute = {};
      this.popoverOpen = false;
    },
    sensorAttributeOpen(row) {//显示传感器属性
      const sensorId = row.sensorId || this.ids
      getSensor(sensorId).then(response => {
        this.sensorAttribute = this.parseJsonString(response.data);
        console.log("this.sensorAttribute:", this.sensorAttribute)
        this.popoverOpen = true;
      })

      // console.log(this.sensorAttribute);
    },

    /** 查询传感器列表 */
    getList() {
      this.loading = true;
      listSensor(this.queryParams).then(response => {
        this.sensorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //将字符串解析成对象
    parseJsonString(jsonString) {
      // console.log(jsonString);
      const string = JSON.parse(jsonString.sensorAttribute);
      console.log("属性：", string)
      const sensorCodeArray = this.dict.type.sensor_code;
      let resultArray = sensorCodeArray.filter(sensor => string.hasOwnProperty(sensor.value))
        .map(sensor => ({ name: sensor.label, value: parseInt(string[sensor.value]) / 10 }));
      resultArray.push({ name: '更新时间', value: jsonString.updateTime })
      console.log("resultArray:", resultArray)
      console.log("sensorCodeArray:", sensorCodeArray)
      return this.transformArray(resultArray);

    },
    transformArray(resultArray) {
      return resultArray.map(item => {
        let newItem = { name: '', value: '', type: 0 };

        // Set name and value
        if (item.name.includes('W')) {
          newItem.name = '室外' + item.name.substring(1);
        } else if (item.name.includes('N')) {
          newItem.name = '室内' + item.name.substring(1);
        } else {
          newItem.name = item.name;
        }

        newItem.value = item.value;

        // Set type based on conditions
        if ((item.name.includes('温度') && item.value > 80) || (item.name === '雨量' && item.value > 0)) {
          newItem.type = 1; // 异常
        }

        // Add units based on name
        if (item.name.includes('温度')) {
          newItem.value += '℃';
        } else if (item.name.includes('湿度')) {
          newItem.value += 'Pa';
        } else if (item.name.includes('风速')) {
          newItem.value += 'm/s';
        } else if (item.name.includes('风力')) {
          newItem.value += '级';
        } else if (item.name === '雨量') {
          newItem.value += 'mm';
        }

        return newItem;
      });


    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sensorId: null,
        sensorName: null,
        sensorType: null,
        sensorAttribute: null,
        locatedAddress: null,
        isNet: null,
        isUsed: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        inoutType: null,
        isPower: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sensorId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加传感器";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sensorId = row.sensorId || this.ids
      getSensor(sensorId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改传感器";
        this.isNet = this.form.isNet;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sensorId != null) {
            updateSensor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSensor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.sensorListAll.total = this.sensorListAll.total + 1
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sensorIds = row.sensorId || this.ids;
      this.$modal.confirm('是否确认删除传感器编号为"' + sensorIds + '"的数据项？').then(function () {
        return delSensor(sensorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        this.sensorListAll.total = this.sensorListAll.total - 1
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sensor/export', {
        ...this.queryParams
      }, `sensor_${new Date().getTime()}.xlsx`)
    },
    getLocatedAddress(index) {
      const entries = this.dict.type.located_address;
      for (let i = 0; i < entries.length; i++) {
        if (entries[i].value == index) {
          return entries[i].label
        }
      }
      return ""
    },
    getSensorType(index) {
      const entries = this.dict.type.inout_type;
      for (let i = 0; i < entries.length; i++) {
        if (entries[i].value == index) {
          return entries[i].label
        }
      }
      return ""
    }
  }
};
</script>
